package com.vogue.supplymall.order.domain.biz.impl;

import java.math.BigDecimal;
import javax.annotation.Resource;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.vogue.configs.springextend.remote.DelegateResource;
import com.vogue.gear.memory.provider.IMemProvider;
import com.vogue.sprakka.client.future.FutureWrapper;
import com.vogue.supplymall.admin.business.common.constant.CachedPayValues;
import com.vogue.supplymall.admin.business.common.constant.CachedTsPayValues;
import com.vogue.supplymall.admin.business.common.inter.bean.InterCachePayValues;
import com.vogue.supplymall.common.constant.ConstantBean;
import com.vogue.supplymall.common.domain.dto.OrderInfo;
import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;
import com.vogue.supplymall.common.domain.tool.VestUtils;
import com.vogue.supplymall.order.domain.biz.OrderPayOnlineBiz;
import com.vogue.supplymall.order.domain.biz.OrderUpdateBiz;
import com.vogue.supplymall.order.exception.PayFailException;
import com.vogue.supplymall.payment.api.WuXiangPayment;
import com.vogue.supplymall.payment.dto.BaseResultParameter;
import com.vogue.supplymall.payment.dto.IResultParameter;
import com.vogue.supplymall.payment.dto.MultiplePayInputParameter;
import com.vogue.supplymall.payment.dto.SinglePayInputParameter;

import org.slf4j.Logger;

/**
 * 线上支付业务处理Worker
 * @author cy
 */
@Service("orderPayOnlineBiz")
public class OrderPayOnlineBizImpl implements OrderPayOnlineBiz {

    public static final Logger LOGGER_ORDERPAYONLINEBIZIMPL = LoggerFactory.getLogger(OrderPayOnlineBizImpl.class);
    
    @Resource
    private OrderUpdateBiz orderUpdateBiz;
    @DelegateResource
    private WuXiangPayment wuXiangPayment;
    @Resource(name = "memProvider")
    private IMemProvider<Object> memProvider;
    @Autowired
    protected MessageSourceUtils messageSourceUtils;
    
    /**
     * 线上支付
     * @param paymode 支付方式 0:线下 1:吾享(商龙云钱包) 2:微信 3:支付宝 4:预付货款
     * @param orderid 订单id
     * @param redirectUrl 支付成功返回的url（只有商龙云钱包支付方式需要）
     */
    public IResultParameter orderPayOnline(Integer paymode, Integer paytypeid, Long orderid, String redirectUrl) {
        IResultParameter result = null;
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOid(String.valueOf(orderid));
        orderInfo.setPaytypeid(paytypeid);
        orderInfo.setRedirectUrl(redirectUrl);
        if (paymode == ConstantBean.EnumPaymentMode.AdvancePayment.getCode()) {
            orderUpdateBiz.payAdvance(orderInfo);
            result = new BaseResultParameter();
            result.setReturnCode(ConstantBean.WUXIANG_SUCCESS_RETURNCODE);
            result.setErrorCode(ConstantBean.WUXIANG_SUCCESS_ERRORCODE.toString());
            result.setErrorText(messageSourceUtils.getMessage("order.pay.success", null));
        } else {
            result = orderUpdateBiz.payOnline(orderInfo);
        }
        return result;
    }
    
    /**
     * 线上支付
     * @param paymode 支付方式 0:线下 1:吾享(商龙云钱包) 2:微信 3:支付宝 4:预付货款
     * @param orderid 订单id
     * @param redirectUrl 支付成功返回的url（只有商龙云钱包支付方式需要）
     * @param amount 支付金额（自己指定）
     */
    public IResultParameter orderPayOnline(Integer paymode, Integer paytypeid, Long orderid, String redirectUrl, BigDecimal amount) {
        IResultParameter result = null;
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOid(String.valueOf(orderid));
        orderInfo.setPaytypeid(paytypeid);
        orderInfo.setRedirectUrl(redirectUrl);
        if (paymode == ConstantBean.EnumPaymentMode.AdvancePayment.getCode()) {
            result = new BaseResultParameter();
            result.setReturnCode(ConstantBean.WUXIANG_SUCCESS_RETURNCODE);
            result.setErrorCode(ConstantBean.WUXIANG_SUCCESS_ERRORCODE.toString());
            result.setErrorText(messageSourceUtils.getMessage("order.pay.success", null));
            result.setData(orderUpdateBiz.payAdvance(orderInfo, amount));
        } else {
            try {
                result = orderUpdateBiz.payOnline(orderInfo, amount);
            } catch (Exception e) {
                LOGGER_ORDERPAYONLINEBIZIMPL.error(e.getMessage());
                throw new PayFailException(e.getMessage());
            }
        }
        return result;
    }

    /**
     * 多单合并支付
     * @param multiplePayInputParameter 封装的订单数据
     * @return 支付结果
     */
    @Override
    public IResultParameter mergePayOnline(MultiplePayInputParameter multiplePayInputParameter) {
        // TODO Auto-generated method stub
        LOGGER_ORDERPAYONLINEBIZIMPL.debug("合并支付参数封装：{}", multiplePayInputParameter.toString());
        InterCachePayValues cachedPayValues = null;
        if (Integer.parseInt(VestUtils.getEntryMode()) + Integer.parseInt(VestUtils.getPayTogether()) == 0) {
            cachedPayValues = (CachedPayValues) memProvider.get(ConstantBean.WUXIANG_CACHED_PAY_VALUES);
        } else {
            cachedPayValues = (CachedTsPayValues) memProvider.get(ConstantBean.WUXIANG_CACHED_TS_PAY_VALUES);
        }
        if (cachedPayValues != null) {
            String payUrl = null;
            if (multiplePayInputParameter.getPaytypeid() == ConstantBean.EnumWuxiangPaytypeid.Alipay.getCode()) {
                payUrl = cachedPayValues.getPayWuxiangCommPayGetUrl();
            } else if (multiplePayInputParameter.getPaytypeid() == ConstantBean.EnumWuxiangPaytypeid.WuXiang.getCode()) {
                payUrl = cachedPayValues.getPayWuxiangPursePayGetUrl();
            } else {
                LOGGER_ORDERPAYONLINEBIZIMPL.error("无效的支付方式：{}", multiplePayInputParameter.getPaytypeid());
                throw new PayFailException(messageSourceUtils.getMessage("order.invalid.onlinePaytype",
                        new Object[]{multiplePayInputParameter.getPaytypeid()}));
            }
            try {
                String publickey64 = cachedPayValues.getPayWuxiangPublickey64();
                String url = payUrl;
                @SuppressWarnings("unchecked")
                FutureWrapper<IResultParameter> wrapper = FutureWrapper.wrapper( wuXiangPayment, gt -> {
                    try {
                        gt.mergePay(multiplePayInputParameter, url, publickey64);
                    } catch (Exception e) {
                        LOGGER_ORDERPAYONLINEBIZIMPL.error(e.getMessage());
                    }
                }, IResultParameter.class );
                return wrapper.get();
            } catch (Exception e) {
                LOGGER_ORDERPAYONLINEBIZIMPL.error("合并支付接口异常：{}", e.getMessage());
                throw new PayFailException(e.getMessage());
            }
//            try {                
//                return wuXiangPayment.mergePay(multiplePayInputParameter, payUrl, publickey64);
//            } catch (Exception e) {
                
//                BaseResultParameter result = new BaseResultParameter();
//                result.setErrorCode("404");
//                result.setReturnCode(0);
//                result.setErrorText("调用接口失败");
//                return result;
//            }
        } else {
            LOGGER_ORDERPAYONLINEBIZIMPL.error("缺少必要支付的配置信息：CachedPayValues");
            throw new PayFailException("缺少必要支付的配置信息");
        }
    }

    /**
     * 单笔支付
     * @param singlePayInputParameter 封装的订单数据
     * @return 支付结果
     */
    @Override
    public IResultParameter singlePayOnline(SinglePayInputParameter singlePayInputParameter) {
     // TODO Auto-generated method stub
        LOGGER_ORDERPAYONLINEBIZIMPL.debug("合并支付参数封装：{}", singlePayInputParameter.toString());
        InterCachePayValues cachedPayValues = null;
        if (Integer.parseInt(VestUtils.getEntryMode()) + Integer.parseInt(VestUtils.getPayTogether()) == 0) {
            cachedPayValues = (CachedPayValues) memProvider.get(ConstantBean.WUXIANG_CACHED_PAY_VALUES);
        } else {
            cachedPayValues = (CachedTsPayValues) memProvider.get(ConstantBean.WUXIANG_CACHED_TS_PAY_VALUES);
        }
        if (cachedPayValues != null) {
            String payUrl = "";
            if (singlePayInputParameter.getPaytypeid() == ConstantBean.EnumWuxiangPaytypeid.Alipay.getCode()) {
                payUrl = cachedPayValues.getPayWuxiangCommPayGetUrl();
            } else if (singlePayInputParameter.getPaytypeid() == ConstantBean.EnumWuxiangPaytypeid.WuXiang.getCode()) {
                payUrl = cachedPayValues.getPayWuxiangPursePayGetUrl();
            } else {
                LOGGER_ORDERPAYONLINEBIZIMPL.error("无效的支付方式：{}", singlePayInputParameter.getPaytypeid());
                throw new PayFailException(messageSourceUtils.getMessage("order.invalid.onlinePaytype",
                        new Object[]{singlePayInputParameter.getPaytypeid()}));
            }
            try {
                String publickey64 = cachedPayValues.getPayWuxiangPublickey64();
                String url = payUrl;
                @SuppressWarnings("unchecked")
                FutureWrapper<IResultParameter> wrapper = FutureWrapper.wrapper( wuXiangPayment, gt -> {
                    try {
                        gt.singlePay(singlePayInputParameter, url, publickey64);
                    } catch (Exception e) {
                        LOGGER_ORDERPAYONLINEBIZIMPL.error(e.getMessage());
                    }
                }, IResultParameter.class );
                return wrapper.get();
            } catch (Exception e) {
                LOGGER_ORDERPAYONLINEBIZIMPL.error("合并支付接口异常：{}", e.getMessage());
                throw new PayFailException(e.getMessage());
            }
            
//            try {
//                return wuXiangPayment.singlePay(singlePayInputParameter, payUrl, cachedPayValues.getPayWuxiangPublickey64());
//            } catch (Exception e) {
//                LOGGER_ORDERPAYONLINEBIZIMPL.error("合并支付接口异常：{}", e.getMessage());
//                throw new PayFailException(e.getMessage());
//                BaseResultParameter result = new BaseResultParameter();
//                result.setErrorCode("404");
//                result.setReturnCode(0);
//                result.setErrorText("调用接口失败");
//                return result;
//            }
        } else {
            LOGGER_ORDERPAYONLINEBIZIMPL.error("缺少必要支付的配置信息：CachedPayValues");
            throw new PayFailException("缺少必要支付的配置信息");
        }
    }
}
